package project.ia04.agents.studio.GUICommunication;

import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import project.ia04.agents.studio.StudioAgent;
import project.ia04.utils.VideoGame;
import jade.core.behaviours.OneShotBehaviour;
import jade.lang.acl.ACLMessage;

public class InitNewGameBehaviour extends OneShotBehaviour {

	private final ACLMessage message;
	private final ObjectMapper mapper = new ObjectMapper();
	private Map<String, Object> map;

	public InitNewGameBehaviour(final ACLMessage message) {
		this.message = message;
	}

	@Override
	public void action() {
		
		//INIT MODEL CURR GAME
		((StudioAgent)myAgent).setCurrentGame(new VideoGame(
				((StudioAgent)myAgent).getFieldDeserialize("title",message.getContent()),
				((StudioAgent)myAgent).getFieldDeserialize("genre", this.message.getContent()),
				((StudioAgent)myAgent).getFieldDeserialize("type", this.message.getContent()),
				getCostDeserialize()));
		//UPDATE CA
		((StudioAgent)myAgent).setCA(((StudioAgent)myAgent).getCA() - ((StudioAgent)myAgent).getCurrentGame().getCost());
		
		//SEND 2 VIEW
		ACLMessage reply = this.message.createReply();
		reply.setPerformative(ACLMessage.INFORM);
		reply.setContent(serialize());
		this.myAgent.send(reply);
	}

	private String serialize(){
		ObjectMapper mapper = new ObjectMapper();
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("title",((StudioAgent)myAgent).getCurrentGame().getTitle());
		map.put("ca",((StudioAgent)myAgent).getCA());
		map.put("type",((StudioAgent)myAgent).getCurrentGame().getGameType());
		map.put("genre",((StudioAgent)myAgent).getCurrentGame().getGameGenre());
		StringWriter sw = new StringWriter();
		try {
			mapper.writeValue(sw,map);
		} catch (JsonGenerationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sw.toString();
	}
	
	@SuppressWarnings("unchecked")
	private float getCostDeserialize() {
		float res = 0;
		try {
			this.map = this.mapper.readValue(this.message.getContent(),
					Map.class);
			res = ((Double)this.map.get("cost")).floatValue();
		} catch (final JsonParseException e) {
			e.printStackTrace();
		} catch (final JsonMappingException e) {
			e.printStackTrace();
		} catch (final IOException e) {
			e.printStackTrace();
		}
		return res;
	}

}
